package com.traffic.between.service;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.gxhl.api.core.tools.ToolSecuritySHA;
import com.traffic.between.config.BetweenProperties;

@SuppressWarnings("deprecation")
public class MaiFengServiceImpl {
	private static Logger logger = Logger.getLogger(MaiFengServiceImpl.class);
	public static MaiFengServiceImpl service = new MaiFengServiceImpl();

	private static String HOST_ORDER_PATH = BetweenProperties.MF_ORDER_URL;
	private static String HOST_ORDERSTATUS_PATH = BetweenProperties.MF_ORDERSTATUS_URL;
	private static String MF_APPKEY = BetweenProperties.MF_APPKEY;
	private static String MF_SECURITYKEY = BetweenProperties.MF_SECURITYKEY;

	@SuppressWarnings({ "resource" })
	public String order(String productId, String phoneNo, String cstmOrderNo) {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d = new Date();

		String time = sdf.format(d);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cust", MF_APPKEY);
		params.put("method","order");
		params.put("time", time);
		params.put("v", "1.1");
		params.put("ruleType", productId);
		params.put("phoneNo", phoneNo);
		params.put("region", "1");
		params.put("cstmOrderNo", cstmOrderNo);

		String paramsSort = ToolSecuritySHA.dataDecrypt(params);
		String sig = getMD5(paramsSort + MF_SECURITYKEY);

		params.put("sig", sig);

		String json = new Gson().toJson(params);

		logger.info("between- 麦峰通信流量订购请求时JSON:  " + json);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(HOST_ORDER_PATH);
		String resultJson = "";
		try {
			if (null != json) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(json, "utf-8");
				entity.setContentEncoding("utf-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}
			HttpResponse result = httpClient.execute(method);
			logger.info("between- 麦峰通信流量订购请求时的响应statusCode: " + result.getStatusLine().getStatusCode());
			if (result.getStatusLine().getStatusCode() == 200) {
				resultJson = EntityUtils.toString(result.getEntity(), "utf-8");
				logger.info("between- 麦峰通信流量订购请求时的响应数据是: " + resultJson);
			}
		} catch (Exception e) {

			logger.error("between- 麦峰通信流量订购请求时的响应异常: " + e);
		
		}
		return resultJson;

	}

	@SuppressWarnings({ "resource" })
	public String orderStatus(String cstmOrderNo) {

		logger.info("between- 麦峰通信订购状态请求参数: params cstmOrderNo = " + cstmOrderNo);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date d = new Date();

		String time = sdf.format(d);

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cust", MF_APPKEY);
		params.put("method","orderStatus");
		params.put("time", time);
		params.put("v", "1.1");
		params.put("cstmOrderNo", cstmOrderNo);

		String paramsSort = ToolSecuritySHA.dataDecrypt(params);
		String sig = getMD5(paramsSort + MF_SECURITYKEY);

		params.put("sig", sig);

		String json = new Gson().toJson(params);

		logger.info("between- 麦峰通信流量订购请求时JSON:  " + json);
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(HOST_ORDERSTATUS_PATH);
		String resultJson = "";
		try {
			if (null != json) {
				// 解决中文乱码问题
				StringEntity entity = new StringEntity(json, "utf-8");
				entity.setContentEncoding("utf-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
			}
			HttpResponse result = httpClient.execute(method);
			logger.info("between- 麦峰通信流量订购请求时的响应statusCode: " + result.getStatusLine().getStatusCode());
			/** 请求发送成功，并得到响应 **/
			if (result.getStatusLine().getStatusCode() == 200) {
				/** 读取服务器返回过来的json字符串数据 **/
				resultJson = EntityUtils.toString(result.getEntity(), "utf-8");
				/** 把json字符串转换成json对象 **/
				logger.info("between- 麦峰通信流量订购请求时的响应数据是: " + resultJson);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("between- 麦峰通信流量订购请求时的响应异常: " + e);
			resultJson = "{\"code\": \"0\",\"msg\":\"请稍后查询\"}";
		}
		return resultJson;

	}
	
	public static String getMD5(String message) {
		System.out.println("getMD5 " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母大写
	}
}
